package com.example.productmanagerspringboot.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.productmanagerspringboot.data.entity.MyUser;
import com.example.productmanagerspringboot.data.pojo.LoginUser;
import com.example.productmanagerspringboot.data.vo.ResponseWithData;
import com.example.productmanagerspringboot.data.vo.UserVO;
import com.example.productmanagerspringboot.mapper.UserMapper;
import com.example.productmanagerspringboot.utils.RedisTokenManager;
import com.example.productmanagerspringboot.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTokenManager redisCache;
    @Autowired
    private UserMapper mapper;

    public ResponseWithData<UserVO> login(MyUser myUser) {
        // AuthenticationManager的authenticate方法进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(myUser.getUsername(), myUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 如果认证没通过，给出对应提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("认证失败！");
        }
        // 如果认证通过了，使用UUID(用户ID)生成JWT
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 把完整的用户信息存入redis
        String uuid = JwtTokenUtils.getUUID();
        String jwt = JwtTokenUtils.createJWT(uuid);
        loginUser.setUuid(uuid);
        redisCache.setCacheObject("login_" + uuid, JSON.toJSONString(loginUser));
        // 把token响应给前端
        return new ResponseWithData<>("登录成功！", 200, new UserVO(jwt, loginUser.getPermission().get(0)));
    }

    public boolean logout() {
        // 获取SecurityContextHolder中的用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String uuid = loginUser.getUuid();
        // 删除redis中的值
        redisCache.deleteObject(loginUser.getUsername());
        return redisCache.deleteObject("login_" + uuid);
    }

    public LoginUser info() {
        // 获取SecurityContextHolder中的用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (LoginUser) authentication.getPrincipal();
    }

    public boolean register(MyUser user) {
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        boolean b = mapper.selectCount(wrapper) > 0;
        if (!b) {
            mapper.insert(user);
        }
        return b;
    }
}
